import { getViewPos, wait, radioChecked, isString, deepCopy, guID } from "@/common.js"
// import { go } from "@/router/index.js"
import { closeCurRoute } from "@/router/tools.js"
import { commonForm } from "./commonForm.js"
import { cusLayoutForm } from "./cusLayoutForm.js"
import { customForm } from "./customForm.js"

// 点击当前条目
export const clickItem = function (item, index) {
  this.dragType = 2
  this.checkedItem = item
  this.curIndex = index
  this.operateForm = radioChecked(this.operateForm, {id: item.id})
  if(item.type == 'split') {
    this.operateForm = _.searchCover(this.operateForm, {id: item.id}, v => ({...v, children: v.children.map(k => ({ ...k, isChecked: false }))}))
  }
}
// 切换表单模式
export const selectItem = function (item) {
  this.radioList = radioChecked(this.radioList, {id: item.id})
}
// 1、记录初始位置（First）
export const getPosition = function () {
  this.operateForm = this.operateForm.map(v => {
    const { left, top } = getViewPos(this.$refs[`card${v.id}`][0])
    return { ...v, top, left}
  })
}
// 转换
export const inverseAni = function () {
  // 3、此时视图尚未更新，赶紧获取结束位置(Last)
  // this.$nextTick(() => {
  //   // 4、拿到结束位置之后，让元素反向通过transform偏移，从而回到最初的位置。未来通过动画的方式进行归位
  //   this.operateForm = this.operateForm.map(v => {
  //     const { left: nowLeft, top: nowTop } = getViewPos(this.$refs[`card${v.id}`][0])
  //     return { ...v, translateX: v.left - nowLeft, translateY: v.top - nowTop, left: nowLeft, top: nowTop } // Inverse偏移
  //   })
  //   // 5、dom回归初始位置之后，开启动画。让其回到默认删除后的位置（Paly执行动画）
  //   this.$nextTick(async () => {
  //     this.isShowAni = true
  //     this.operateForm = this.operateForm.map(v => {
  //       getViewPos(this.$refs[`card${v.id}`][0])
  //       return { ...v, translateX: 0, translateY: 0 }
  //     })
  //     await wait(500)
  //     this.isShowAni = false
  //   })
  // })
}
// 删除当前条目
export const delItem = function (item) {
  // 2、删除并触发dom更新
  this.operateForm = this.operateForm.filter(v => v.id != item.id)  //！！！！！！！基本上只要改这里的代码即可。其他几个步骤很固定了。记录初始位置、偏移、开启动画归位
  this.inverseAni()
}
/*
 ************************************************************
 * 从左边拖到中间
 * @param {*} item 
 *************************************************************
 */
// 表单类型拖拽开始
export const formTypeDragStart = function (item) {
  this.dragType = 1
  // console.log(this.direction)
  const id = guID()
  const newItem = Object.keys(item).reduce((prev, v) => {
    // const mapKey = {'key':'value', 'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
    // 通用表单是可能，重复使用的。所以必须控制一下。不然key值会重复
    if(v.includes('key') && (!item.isCustomField || item.type == 'bloodPressure')) {
      prev[v] = `${item[v].split('_')[0]}_${id}`
    } else {
      prev[v] = item[v]
    }
    return prev
  }, {})
  this.curFormObj = deepCopy({...newItem, id, isChecked: true, children: (newItem.children || []).map(v => ({...v, id: _.guID()}))})
  this.checkedItem = {}
}
// 拖拽进入盒子
export const dragenterInBox = function (e) {
  this.mouseHoverItem = {id: -1}
}
// 拖转进入盒子并释放
export const dragInBox = function (e) {
  if(this.dragType == 2 && this.mouseHoverItem.id != -1) {return }
  let operateForm = this.operateForm.filter(v => v.id !== this.curFormObj.id)
  this.operateForm = [...operateForm.map(v => ({...v, isChecked: false})), {...this.curFormObj, isChecked: true}]
}
// 拖拽结束
export const dragEnd = function (e) {
  this.mouseHoverItem = {}
}
/*
 ************************************************************
 * 中间表单改变顺序
 * @param {*} item 
 *************************************************************
 */
// 开始拖拽
export const dragstart = function (e, index, item) {
  this.dragType = 2
  this.curIndex = index
}
// 进入目标区域
export const dragenter = async function (e, index, item) {
  // console.log('2、dragenter')
  // console.log(item)
  // if(this.operateForm[index].type == 'split') { return false }
  // console.log(index)
  if(this.dragType == 2) {
    this.direction = this.curIndex > index ? 'top' : this.curIndex < index ? 'bottom' : 'bottom'
  } else {
    this.direction = 'top'
  }
  this.mouseHoverItem = item
}
// 防止表单旁边。鼠标释放
export const dropCurBox = function (e, index) {
  if(this.dragType == 1) {
    const operateForm = this.operateForm.filter(v => v.id != this.curFormObj.id)
    this.operateForm = [...operateForm.slice(0, index).map(v => ({...v, isChecked: false})), {...this.curFormObj, isChecked: true}, ...operateForm.slice(index).map(v => ({...v, isChecked: false}))]
  } else if(this.dragType == 2 && this.curIndex != index){
    const operateForm = this.operateForm.filter((v, i) => i !== this.curIndex)
    this.operateForm = [...operateForm.slice(0, index), this.operateForm[this.curIndex], ...operateForm.slice(index)]
    this.curIndex = index
    this.inverseAni()
  }
  e.preventDefault()
}
/*
 ************************************************************
 * 业务逻辑
 *************************************************************
 */
// 生成表单
export const submit = async function () {
  console.log(this.operateForm)
  // this.$refs['formDesc'].validate(async (valid) => {
  //   if (!valid) { return this.$Message.error('有必填项未填') }
  //   const {name, visitType, illustrate} = this.formData
  //   const res = await this.$post('/admin-api/diag/followupForm/addCusForm', {
  //     id: this.$route.query.formId || '',  name, illustrate, 
  //     // visitType,
  //     formType: this.$route.query.formType, formContent: JSON.stringify(this.operateForm), 
  //   })
  //   if(res) {
  //     this.$Message.success(this.$route.query.formId ? '表单编辑成功' : '表单新增成功')
  //     await wait(600)
  //     closeCurRoute.call(this)
  //     go({name: '/systemManage/templateManage/visitForm'})
  //   }
  // })
}
// 获取表单列表
export const getFormList = async function () {
  if(!this.$route.query.formId) { return false }
  return this.$post('/admin-api/diag/followupForm/formDetail', { id: this.$route.query.formId}).then(({name, illustrate, formContent}) => {
    this.formData = { name, illustrate }
    let operateForm = isString(formContent) ? JSON.parse(formContent) : formContent
    this.operateForm = operateForm.map(v =>{
      const curItem = [...commonForm, ...cusLayoutForm, ...customForm].find(k => k.type == v.type) || {} // 假如新增的字段
      return  { ...curItem, ...v, isChecked: false }
    })
  })
}
// 绑定箭头事件
export const bindArrow = function () {
  _.listenKey(this, {
    Delete: () => { // 按下删除按键
      this.delItem(this.checkedItem)
      this.checkedItem = {}
    },
    ArrowUp: () => { // 按下向上的箭头
      if(this.curIndex <= 0) { return }
      const operateForm = this.operateForm.filter(v => v.id != this.checkedItem.id)
      this.operateForm = [...operateForm.slice(0, this.curIndex - 1), this.checkedItem, ...operateForm.slice(this.curIndex - 1)]
      this.curIndex = this.curIndex - 1
      this.inverseAni()
    },
    ArrowDown: () => { // 按下向下的箭头
      if(this.curIndex >= this.operateForm.length - 1) { return }
      const operateForm = this.operateForm.filter(v => v.id != this.checkedItem.id)
      this.operateForm = [...operateForm.slice(0, this.curIndex + 1), this.checkedItem, ...operateForm.slice(this.curIndex + 1)]
      this.curIndex = this.curIndex + 1
      this.inverseAni()
    }
  })
}
// 预览表单
export const previewForm = function () {
  this.modalType = 3
}
// 导出json
export const exportJson = async function () {
  this.isShowExportJson = true
  if(this.operateForm.length == 0) { await this.getFormList() }
}
// 显示导入json弹框
export const showImportJson = function () {
  this.isShowImportJson = true
}

// 设置弹框显隐
export const setModalType = function (e) {
  this.modalType = e
  if(!e) {
    let operateForm = this.operateForm
    const spreadList = operateForm.filter(v => v.type == 'text' && _.trim(v.spreadField, 1))
    const isCurItem = (p, spreadField) => _.safeGet(() => _.difference([p.key, p.key1, p.key2], _.trim(spreadField, 1).split(',')).length != 3, false)
    spreadList.forEach(v => {
      operateForm = operateForm.map(k => {
        if(k.id == v.id) {
          k.isSpread = v._isSpread // 恢复为原始的是否展开的默认值
        } else if(k.type == 'split') {
          k.children = k.children.map(h => (isCurItem(h, v.spreadField) && (h.isShow = v._isSpread), h)) // 恢复为原始的是否展开的默认值
        } else {
          isCurItem(k, v.spreadField) && (k.isShow = v._isSpread) // 恢复为原始的是否展开的默认值
        }
        return k
      })
    })
    this.operateForm = operateForm
  }
}